package com.yao.system.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
public class ThreadPoolConfig {

    /**
     * 自定义线程池
     * 核心线程数: 6
     * 最大线程数: 6
     * 救急线程存活时间: 5分钟
     * 拒绝策略: 调用者自己执行任务
     *
     * @return
     */
    @Bean
    public ThreadPoolExecutor coreThreadPool() {
        return new ThreadPoolExecutor(6, 6,
                300, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(99),
                new ThreadFactory() {
                    AtomicInteger threadNumber = new AtomicInteger(0);

                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(() -> r.run(),
                                "coreThreadPool-" + threadNumber.getAndIncrement());
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy());
    }


    @Bean
    public ThreadPoolExecutor jobThreadPool() {
        return new ThreadPoolExecutor(6, 6,
                300, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(99),
                new ThreadFactory() {
                    AtomicInteger threadNumber = new AtomicInteger(0);

                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(() -> r.run(),
                                "jobThreadPool-" + threadNumber.getAndIncrement());
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy());
    }
}
